package yuyicman.display 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import yuyicman.debug.Debugger;
	
	/**
	 * ...
	 * @author Yuyic.
	 */
	public class MovieClipButton extends MovieClip implements IButton
	{
		
		
		public function MovieClipButton() 
		{
			super();
			_init();
		}
		
		private function _init():void {
			
			buttonMode = true;
			stop();
			addEventListener( MouseEvent.MOUSE_OVER, _mousehandler );
			addEventListener( MouseEvent.MOUSE_OUT, _mousehandler );
			
		}
		
		public function forEnd():void {
			addEventListener( Event.ENTER_FRAME, forward );
			if( hasEventListener( Event.ENTER_FRAME ) ){
				removeEventListener( Event.ENTER_FRAME, backward );
			}
		}
		
		public function forStart():void {
			addEventListener( Event.ENTER_FRAME, backward );
			if( hasEventListener( Event.ENTER_FRAME ) ){
				removeEventListener( Event.ENTER_FRAME, forward );
			}
		}
		
		private function _mousehandler( e:MouseEvent ):void {
			
			if ( e.type == MouseEvent.MOUSE_OVER ) {
				forEnd();
			}
			
			else if ( e.type == MouseEvent.MOUSE_OUT ) {
				forStart();
			}
			
		}
		
		private function backward( e:Event ):void {
			
			if ( currentFrame == 1 ) {
				removeEventListener( Event.ENTER_FRAME, backward );
				return;
			}
			
			prevFrame();
			
		}
		
		private function forward( e:Event ):void {
			
			if ( currentFrame == totalFrames ) {
				removeEventListener( Event.ENTER_FRAME, forward );
				return;
			}
			
			nextFrame();
			
		}
		
		
		
		public function destroy():void {
			
			removeEventListener( Event.ENTER_FRAME, backward );
			removeEventListener( Event.ENTER_FRAME, forward );
			removeEventListener( MouseEvent.MOUSE_OVER, _mousehandler );
			removeEventListener( MouseEvent.MOUSE_OUT, _mousehandler );
			if ( parent ) {
				parent.removeChild( this );
			}
		}
		
		public function set select( value:Boolean ):void {
			
			if ( value ) {
				removeEventListener( MouseEvent.MOUSE_OVER, _mousehandler );
				removeEventListener( MouseEvent.MOUSE_OUT, _mousehandler );
				forEnd();
				dispatchEvent( new Event("select") );
			}
			else {
				
				addEventListener( MouseEvent.MOUSE_OVER, _mousehandler );
				addEventListener( MouseEvent.MOUSE_OUT, _mousehandler );
				forStart();
			}
			
		}
		
		
	}

}